package com.inspur.cmis.base.custmanger.action;

import com.inspur.cmis.base.custmanger.model.CmInfoBean;
import com.inspur.cmis.base.custmanger.model.CmLevelBean;
import com.inspur.cmis.base.custmanger.service.CmInfoService;
import com.inspur.cmis.base.custmanger.service.CmLevelService;
import com.inspur.common.model.Pagination;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cmLevel")
public class CmlevelController {

    private static final Logger log = LoggerFactory.getLogger(CmlevelController.class);

    @Autowired
    CmLevelService cmLevelService;
    @Autowired
    CmInfoService cmInfoService;
    @Resource
    HttpServletRequest request;

    @RequestMapping("/list")
    public String cmlevelList(Pagination<CmLevelBean> page,CmLevelBean cmLevelBean, Model model){
        page.setQueryObject(cmLevelBean);
        cmLevelService.getListByPage(page);
        request.setAttribute("cmLevelList", page);
        log.debug("RequestMapping list");
        model.addAttribute("cmLevelBean",cmLevelBean);
        model.addAttribute("cmInfo",cmInfoService.selectAll());
        return "base/manager/clientMgrInfoOther";
    }


    @InitBinder
    private void customizeBinding ( WebDataBinder binder) {

        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        dateFormatter.setLenient(false);
        binder.registerCustomEditor(Date.class, "holdDate",
                new CustomDateEditor(dateFormatter, true));

    }
    @RequestMapping(value = "/expExcel", method = RequestMethod.GET)
    public void expExcel(Integer key,
                         HttpServletResponse response) throws Exception{
        Workbook wb = new HSSFWorkbook();
        Sheet sheet=wb.createSheet();
        // Create a row and put some cells in it. Rows are 0 based.
        Row row = sheet.createRow(0);
// Create a cell and put a value in it.
        Cell cell = row.createCell(0);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue("证件号");
        List list=cmInfoService.selectAll();
        int i=1;
        for(Object cmInfoBean:list){
            cmInfoBean=(CmInfoBean)cmInfoBean;
            row = sheet.createRow(i);
            cell = row.createCell(0);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(((CmInfoBean) cmInfoBean).getId());
            cell = row.createCell(1);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(((CmInfoBean) cmInfoBean).getName());
            cell = row.createCell(2);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(((CmInfoBean) cmInfoBean).getSsn());
            i++;
        }

        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename=abc.xls");
        //IOUtils.copy(inputStream, response.getOutputStream());
        wb.write(response.getOutputStream());
        response.flushBuffer();

    }
    @RequestMapping("/impExcel")
    public String impExcel(@RequestParam MultipartFile attachmentfile) throws Exception{
        String url="base/manager/clientMgrInfoOther";
        InputStream inputStream=attachmentfile.getInputStream();
        Workbook wb = WorkbookFactory.create(inputStream);
        Sheet sheet=wb.getSheetAt(0);

//        int rowStart = Math.min(15, sheet.getFirstRowNum());
//        int rowEnd = Math.max(1400, sheet.getLastRowNum());
//        log.debug("rowStart"+rowStart+"rowEnd"+rowEnd);
        int rowNum=0;
        for (Row row : sheet) {
            rowNum++;
            if(rowNum>1){
                int cellNum=0;
                for (Cell cell : row) {
                    // Do something here
                    cellNum++;
                    String val="";
                    if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
                        cell.setCellType(cell.CELL_TYPE_STRING);
                        val=""+cell.getStringCellValue();
                    }else{
                        val=cell.getStringCellValue();
                    }

                    log.debug("cellVal:"+val);
                }
            }

        }

        inputStream.close();
        return url;
    }
    @RequestMapping("/create")
    public String create(@RequestParam MultipartFile attachmentfile, @RequestParam String cmId , @RequestParam("holdDate") String holdDate, Model model) throws Exception{
        Pagination<CmLevelBean> page = new Pagination<CmLevelBean>(1, 10);
        CmLevelBean cmLevelBean=new CmLevelBean();
        if(attachmentfile!=null && attachmentfile.getSize()>0) {
            cmLevelBean.setAttachmentOri(attachmentfile.getOriginalFilename());
            String[] arr = attachmentfile.getOriginalFilename().split("\\.");
            String suffix = "";
            if (arr.length >= 2) {
                suffix = "." + arr[arr.length - 1];
            }
            cmLevelBean.setAttachment(System.currentTimeMillis() + suffix);
            String realPath = request.getServletContext().getRealPath("/WEB-INF/upload/" + cmLevelBean.getAttachment());

            File file = new File(request.getServletContext().getRealPath("/WEB-INF/upload/"));
            if (!file.exists()) {
                file.mkdir();
            }
            file = new File(realPath);
            attachmentfile.transferTo(file);
        }
        cmLevelBean.setCmId(new Integer(cmId));
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        if (holdDate!=null)
            cmLevelBean.setHoldDate(dateFormatter.parse(holdDate));
        cmLevelService.create(cmLevelBean);
        cmLevelService.getListByPage(page);
        request.setAttribute("cmLevelList", page);
        model.addAttribute("cmLevelBean",cmLevelBean);
        model.addAttribute("cmInfo",cmInfoService.selectAll());
        String url="base/manager/clientMgrInfoOther";
        return url;
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadFile(Integer key,
                             HttpServletResponse response) throws Exception{
        CmLevelBean cmLevelBean=cmLevelService.selectById(key);
        File fileToDownload = new File(request.getServletContext().getRealPath("/WEB-INF/upload/"+cmLevelBean.getAttachment()));
        InputStream inputStream = new FileInputStream(fileToDownload);
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(cmLevelBean.getAttachmentOri(),"UTF-8"));
        IOUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();
        inputStream.close();
    }

}
